from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app.models import UserSettings, db
from datetime import datetime

bp = Blueprint('settings', __name__)


@bp.route('/get_settings', methods=['GET'])
@login_required
def get_settings():
    settings = current_user.settings
    if not settings:
        # 创建默认设置
        settings = UserSettings(user_id=current_user.id)
        db.session.add(settings)
        db.session.commit()

    return jsonify({
        'max_tokens': settings.max_tokens,
        'temperature': settings.temperature,
        'top_p': settings.top_p,
        'presence_penalty': settings.presence_penalty,
        'frequency_penalty': settings.frequency_penalty
    })


@bp.route('/update_settings', methods=['POST'])
@login_required
def update_settings():
    data = request.get_json()
    settings = current_user.settings

    if not settings:
        settings = UserSettings(user_id=current_user.id)
        db.session.add(settings)

    if 'max_tokens' in data:
        settings.max_tokens = int(data['max_tokens'])
    if 'temperature' in data:
        settings.temperature = float(data['temperature'])
    if 'top_p' in data:
        settings.top_p = float(data['top_p'])
    if 'presence_penalty' in data:
        settings.presence_penalty = float(data['presence_penalty'])
    if 'frequency_penalty' in data:
        settings.frequency_penalty = float(data['frequency_penalty'])

    settings.updated_at = datetime.utcnow()
    db.session.commit()

    return jsonify({'success': True})
